package com.tangw.spring.dao.common;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.google.common.base.Preconditions;

@SuppressWarnings("unchecked")
public abstract class AbstractHibernateDao<T extends Serializable> implements BaseOperationDao<T> {

	private Class<T> clazz;

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	protected final void setClazz(final Class<T> clazz) {
		this.clazz = Preconditions.checkNotNull(clazz);
	}

	protected final Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public T findOne(Integer id) {
		return (T) getCurrentSession().get(clazz, id);
	}

	@Override
	public List<T> findAll() {
		return getCurrentSession().createQuery(" from " + clazz.getName()).list();
	}

	@Override
	public void create(T entity) {
		Preconditions.checkNotNull(entity);
		getCurrentSession().saveOrUpdate(entity);
	}

	@Override
	public T update(T entity) {
		Preconditions.checkNotNull(entity);
		getCurrentSession().update(entity);
		return entity;
	}

	@Override
	public void delete(T entity) {
		Preconditions.checkNotNull(entity);
		getCurrentSession().delete(entity);
	}

	@Override
	public void deleteById(Integer id) {
		final T entity = findOne(id);
		Preconditions.checkNotNull(entity);
		delete(entity);
	}

}
